package org.eclipseuseradmin.internal.ui.security;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.security.auth.Subject;

import org.eclipse.ui.AbstractSourceProvider;
import org.eclipse.ui.ISources;

public class UserAdminSourceProvider extends AbstractSourceProvider {

	public static final String NAME = "org.eclipseuseradmin.ui.username";

	public static final String ROLES = "org.eclipseuseradmin.ui.userroles";

	private String userName;

	private List<String> userRoles;

	public void dispose() {
	}

	public Map<String, Object> getCurrentState() {

		Map<String, Object> map = new HashMap<String, Object>(1);

		map.put(NAME, userName);
		map.put(ROLES, userRoles);
		return map;
	}

	public String[] getProvidedSourceNames() {
		return new String[] { NAME, ROLES };
	}

	public void setSubject(Subject subject) {

		this.userName = getUserName(subject);
		this.userRoles = getUserRoles(subject);
		fireSourceChanged(ISources.WORKBENCH, getCurrentState());
	}

	private String getUserName(Subject subject) {

		if (subject == null) {
			return null;
		}

		Set<RolePrincipal> rolePrincipals = subject
				.getPrincipals(RolePrincipal.class);
		for (RolePrincipal rolePrincipal : rolePrincipals) {
			return rolePrincipal.getName();
		}
		return null;
	}

	private List<String> getUserRoles(Subject subject) {

		if (subject == null) {
			return new ArrayList<String>();
		}

		Set<RolesPrincipal> rolesPrincipals = subject
				.getPrincipals(RolesPrincipal.class);
		for (RolesPrincipal rolesPrincipal : rolesPrincipals) {
			Enumeration<RolePrincipal> rolePrincipals = rolesPrincipal
					.members();
			List<String> roleNames = new ArrayList<String>();
			while (rolePrincipals.hasMoreElements()) {
				roleNames.add(rolePrincipals.nextElement().getName());
			}
			return roleNames;
		}
		return new ArrayList<String>();
	}

}
